﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LumiSoft.Net.IMAP;
using LumiSoft.Net.IMAP.Client;
using LumiSoft.Net;
using System.Configuration;
using System.Text.RegularExpressions;

namespace uTorrentRemote.TokenSources.Imap
{
    public class ImapTokenSource : ITokenSource
    {
        private bool isInitiated = false;
        private int currentIndex = 0;
        private DateTime lastInitDateStamp = DateTime.MinValue;
        private List<Token> tokens = new List<Token>();

        private ILog log;
        public ImapTokenSource(ILog log)
        {
            this.log = log;
            log.Write("Looking for commands in " + ConfigurationManager.AppSettings["imap_email"]);
        }

        private void init()
        {
            tokens.Clear();
            currentIndex = 0;
            tokens = new List<Token>();
            
            using (ImapWrapper imapWrapper = new ImapWrapper(log))
            {
                List<ImapMessage> messages = imapWrapper.GetUnseenMessages("utorrent");
                if (messages != null)
                {
                    log.Write("Received messages: " + messages.Count.ToString());
                    foreach (ImapMessage message in messages)
                    {
                        Regex regex = new Regex(@"http\://rutracker\.org/forum/viewtopic\.php\?t=\d+", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                        MatchCollection matchCollection = regex.Matches(message.Body);
                        foreach (Match match in matchCollection)
                        {
                            Token token = new Token(match.Value);
                            if (!tokens.Contains<Token>(token))
                                tokens.Add(token);
                        }
                        imapWrapper.MarkSeen(message);
                    }
                }
            }

            isInitiated = true;
            lastInitDateStamp = DateTime.Now;
        }

        private bool isTimeToReinit()
        {
            if(currentIndex >= tokens.Count)
            {
                TimeSpan ts = DateTime.Now - lastInitDateStamp;
                if (ts.TotalSeconds > 60)
                    return true;
            }
            return false;
        }

        public bool IsNextTokenAvailable()
        {
            if (!isInitiated) init();
            if (isTimeToReinit()) init();

            if (tokens == null || tokens.Count == 0)
                return false;

            if (currentIndex >= tokens.Count)
                return false;

            return true;
        }

        public Token FetchNextToken()
        {
            if (!isInitiated) init();
            if (isTimeToReinit()) init();

            if (tokens == null || tokens.Count == 0)
                return null;

            if (currentIndex >= tokens.Count)
                return null;

            Token token = tokens[currentIndex];

            currentIndex++;
            return token;
        }
    }
}
